﻿using DocumentFormat.OpenXml.Drawing.Diagrams;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace FileManager.Util
{
    class HashHelper
    {
        private static HashAlgorithm hash256 = SHA256.Create();
        public static string GetFileHash256(string fileName)
        {
            return GetFileHash(fileName,hash256);
        }

        public static string GetSteamHash(Stream stream)
        {
            lock (hash256)
            {
                // 计算文件哈希值
                byte[] hashBytes = hash256.ComputeHash(stream);
                // 将哈希字节数组转换为十六进制字符串
                StringBuilder sb = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    sb.Append(b.ToString("x2")); // 使用小写的十六进制字符
                }
                return sb.ToString();
            }
        }

        private static string GetFileHash(string filePath, HashAlgorithm algorithm)
        {
            // 检查文件是否存在
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"The file '{filePath}' does not exist.");
            }
            lock(hash256)
            {
                // 打开文件流
                using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    // 计算文件哈希值
                    byte[] hashBytes = algorithm.ComputeHash(fileStream);
                    // 将哈希字节数组转换为十六进制字符串
                    StringBuilder sb = new StringBuilder();
                    foreach (byte b in hashBytes)
                    {
                        sb.Append(b.ToString("x2")); // 使用小写的十六进制字符
                    }

                    return sb.ToString();
                }
            }
        }
    }
}
